from pyecharts.charts import Line, Bar, Pie, Scatter, TreeMap
from pyecharts import options as opts
from pyecharts.globals import ThemeType
from gcz_common.config import config
dataList = []
def parse(data):
    global dataList
    dataList = []
    dateList = []
    categoryList = []
    nationList = []
    for item in data:
        name = item[2]
        score = item[4]
        info = item[7].replace("\xa0", "").replace("\\", "").replace("...", "").split("/")
        category = info[-1].split(" ")
        for cat in category:
            if cat not in categoryList:
                categoryList.append(cat)
        nation = info[-2].split(" ")
        for nat in nation:
            if nat not in nationList:
                nationList.append(nat)
        date = info[-3].split(" ")[-1]
        if date not in dateList:
            dateList.append(date)
        dataList.append({"name": name, "score": score, "category": category, "nation": nation, "date": date})

    nationList.sort()
    dateList.sort()
    categoryList.sort()
    return [nationList, dateList, categoryList]

def analyseNation(params=[[], []]):
    data = dataList.copy()
    if len(params[0]) != 0 or len(params[1])!=0:
        for i in range(len(dataList)-1, -1, -1):
            if len(params[0]) != 0:
                tag = False
                for nat in data[i]['nation']:
                    if nat in params[0]:
                        tag = True
                        break
                if not tag:
                    data.remove(data[i])
                    continue
            if len(params[1]) != 0:
                if data[i]['date'] not in params[1]:
                    data.remove(data[i])
                    continue

    nationCount = {}
    for item in data:
        if len(params[0]) != 0:
            for nat in item['nation']:
                if nat in params[0]:
                    dictCountAdd(nationCount, [nat])
        else:
            dictCountAdd(nationCount, item['nation'])
    treeMap(nationCount)

def analyseScore(params=[[],[],[]]):
    data = dataList.copy()

    if len(params[0]) != 0 or len(params[1])!=0 or len(params[2])!=0:
        for i in range(len(dataList)-1, -1, -1):
            if len(params[0]) != 0:
                if data[i]['category'] not in params[0]:
                    tag = False
                    for cat in data[i]['category']:
                        if cat in params[0]:
                            tag = True
                            break
                    if not tag:
                        data.remove(data[i])
                        continue
            if len(params[1]) != 0:
                if data[i]['nation'] not in params[1]:
                    tag = False
                    for nat in data[i]['nation']:
                        if nat in params[1]:
                            tag = True
                            break
                    if not tag:
                        data.remove(data[i])
                        continue
            if len(params[2]) != 0:
                if data[i]['date'] not in params[2]:
                    data.remove(data[i])
                    continue


    scoreDict = {}
    for item in data:
        dictCountAdd(scoreDict, [str(item['score'])])
    keys = []
    for key in scoreDict.keys():
        keys.append(float(key))
    bar([keys, list(scoreDict.values())])

def dictCountAdd1(data, key1, key2, value1):
    if key1 not in data.keys():
        data[key1] = value1.copy()
    if key2 in data[key1]:
        data[key1][key2] += 1
    else:
        data[key1][key2] = 1

def dictCountAdd(data, keys):
    for key in keys:
        if key not in data.keys():
            data[key] = 1
        else:
            data[key] += 1

def dictAdd(data, key, value):

    if key not in data.keys():
        data[key] = [value]
    else:
        data[key].append(value)

def treeMap(dataList):
    data = []
    for key in dataList:
        data.append({"value": dataList[key], "name": f"{key}:{dataList[key]}"})
    tm = (
        TreeMap()
        .add("出品地区", data)
        .set_series_opts(label_opts=opts.LabelOpts(position='inside'))
        .set_global_opts(title_opts=opts.TitleOpts(title='矩形树图', subtitle='GCZ组'))
    )

    tm.render(config.file.echartPath+config.file.pieFileName+".html")

def bar(data):
    y_data = data[1]
    x_data = data[0]

    bar = (
        Bar()
        .add_xaxis(x_data)
        .add_yaxis("",
                   y_data)
        .set_series_opts(
            label_opts=opts.LabelOpts(is_show=False),
            markpoint_opts=opts.MarkPointOpts(data=[
                {"type": 'max', 'name': '最大值'},
                {"type": 'min', 'name': '最小值'}
            ])
        )
        .set_global_opts(
            title_opts=opts.TitleOpts(
                title="立方图"
            ),
            datazoom_opts=opts.DataZoomOpts(is_show=True, range_start=0, range_end=100),
            xaxis_opts=opts.AxisOpts(
                type_='category',
                name='评分',
                name_textstyle_opts={'padding': [0, 0, -30, 10]}
            ),
            yaxis_opts=opts.AxisOpts(
                type_='value',
                name='评分数量',
                name_textstyle_opts={'padding': [200, 0, -20, -100]}
            )
        )
    )
    # 生成echars图片网页
    bar.render(config.file.echartPath+config.file.barFileName+".html")